package com.ruoyi.system.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ByWxQrcodeService;
import org.apache.commons.io.IOUtils;
import org.apache.poi.hpsf.Decimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.IByOrderService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-05-27
 */
@Service
public class ByOrderServiceImpl implements IByOrderService {
    @Autowired
    private ByOrderMapper byOrderMapper;

    @Autowired
    private DateUtilSqlMapper dateUtilSqlMapper;

    @Autowired
    private ByJzMapper jzMapper;

    @Autowired
    private ByBsMapper bsMapper;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private ByWxUserMapper wxUserMapper;

    @Autowired
    private ByParamMapper paramMapper;

    @Autowired
    private ByOrderPayLogMapper orderPayLogMapper;

    @Autowired
    private ByBsTimeMapper bsTimeMapper;

    @Autowired
    private ByOrderEvalMapper orderEvalMapper;

    @Autowired
    private ByWxQrcodeService wxQrcodeService;

    @Autowired
    private ByJzYhqMapper byJzYhqMapper;

    @Autowired
    private ByCouponUserMapper byCouponUserMapper;


    @Override
    public List<JSONObject> getBsEvalById(JSONObject json) {
        String id = json.getString("id");
        List<JSONObject> list = orderEvalMapper.getByOrderEvalList(id);

        return list;
    }

    @Override
    public JSONObject orderDetailById(JSONObject json) {
//        String wxid = json.getString("wxid");
        String orderid = json.getString("orderid");
        return byOrderMapper.orderDetailById(orderid);
    }

    @Override
    public Object orderTimeMananger(JSONObject json) {
        String wxid = json.getString("wxid");
        String orderid = json.getString("orderid");
        JSONObject rjson = new JSONObject();
        ByOrder orderDetail = byOrderMapper.selectByOrderById(Long.parseLong(orderid));// 获取订单详情
        ByBs bsDetail = bsMapper.selectByBsById(Long.parseLong(orderDetail.getBsId()));// 获取帮手详情
        if(bsDetail.getWxid().trim().equals(wxid.trim())){
            // 进行判断是开始计时 还是结束计时
            if(StringUtils.isEmpty(orderDetail.getStarttime())){ // 进行开启计时
                byOrderMapper.startWxCodeOrder(orderDetail.getId()+"");

                rjson.put("status",true);
                rjson.put("msg","帮手计时开始！");
                return rjson;
            }else if(StringUtils.isEmpty(orderDetail.getEndtime())){// 帮手扫码计时结束
                // byOrderMapper.stopOrder(orderDetail.getId()+"");
                json.put("id",orderid);
                stopOrder(json);
                rjson.put("status",true);
                rjson.put("msg","帮手计时结束！");
                return rjson;
            }else{
                rjson.put("status",false);
                rjson.put("msg","订单已结束！");
                return rjson;
            }
        }else{
            rjson.put("status",false);
            rjson.put("msg","你没有权限操作！");
        }
        rjson.put("status",false);
        rjson.put("msg","你没有权限操作！");
        return rjson;
    }

    @Override
    public Object saveOrderEval(JSONObject json) {
        String orderid = json.getString("orderid");
        String wxid = json.getString("wxid");
        String content = json.getString("content");
        String star = json.getString("star");
        JSONObject rjson = new JSONObject();
        if(StringUtils.isEmpty(wxid)){
            rjson.put("status","0");
            rjson.put("msg","没有授权的微信用户！");
            return rjson;
        }


        ByOrder order = byOrderMapper.selectByOrderById(Long.parseLong(orderid));
        ByOrderEval orderEval = new ByOrderEval();
        orderEval.setOrderId(orderid);
        orderEval.setWxId(wxid);
        orderEval.setAddtime(dateUtilSqlMapper.getNowDateTime());
        int starNum = Integer.parseInt(star);
        starNum = starNum + 1;
        if(starNum > 5){
            starNum = 5;
        }
        orderEval.setStar(starNum+"");
        orderEval.setContent(content);
        orderEval.setBsId(order.getBsId());

        // 进行帮手评价的计算
        ByBs bs = bsMapper.selectByBsById(Long.parseLong(order.getBsId()));
        int disCount = Integer.parseInt(bs.getDiscount())+1;
        bs.setDiscount(disCount+"");
        bsMapper.updateByBs(bs);

        orderEvalMapper.insertByOrderEval(orderEval);
        rjson.put("status","1");
        rjson.put("msg","保存成功！");

        return rjson;
    }

    @Override
    public Object payPayOrder(JSONObject body, HttpServletRequest request) {
        String wxid = body.getString("wxid"); // 获取微信id
        String id = body.getString("id");  // 获取订单id
        ByWxUser userEntity = wxUserMapper.selectByWxUserById(wxid);
        String orderSn = IdUtils.simpleUUID(); // 进行生成订单编号
        // 进行更新订单信息
        ByOrder order = byOrderMapper.selectByOrderById(Long.parseLong(id));
        order.setPayId(orderSn);
        byOrderMapper.updateByOrder(order);

        // 进行生成支付日志_____进行保存
        ByOrderPayLog orderPayLog = new ByOrderPayLog();
        orderPayLog.setOrderSn(orderSn);
        orderPayLog.setPrice(order.getPayprice().toString());
        orderPayLog.setAddtime(dateUtilSqlMapper.getNowDateTime());
        orderPayLog.setOrderId(id);
        orderPayLog.setWxId(wxid);
        orderPayLogMapper.insertByOrderPayLog(orderPayLog);


        WxPayMpOrderResult result = null;
        try {
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setOutTradeNo(orderSn);
            orderRequest.setOpenid(userEntity.getWeixinOpenid());
            orderRequest.setBody("订单：" + orderSn);
            // 元转成分
            int fee = 0;
            BigDecimal actualPrice = order.getPayprice();// BigDecimal.valueOf(order.getPayprice());
            fee = actualPrice.multiply(new BigDecimal(100)).intValue();
            orderRequest.setTotalFee(fee);
            orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(request));
            result = wxPayService.createOrder(orderRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public Object payNotify(HttpServletRequest request, HttpServletResponse response) {
        String xmlResult = null;
        try {
            xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        } catch (IOException e) {
            e.printStackTrace();
            return WxPayNotifyResponse.fail(e.getMessage());
        }

        WxPayOrderNotifyResult result = null;
        try {
            result = wxPayService.parseOrderNotifyResult(xmlResult);

            if(!WxPayConstants.ResultCode.SUCCESS.equals(result.getResultCode())){
//                logger.error(xmlResult);
                throw new WxPayException("微信通知支付失败！");
            }
            if(!WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())){
//                logger.error(xmlResult);
                throw new WxPayException("微信通知支付失败！");
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            return WxPayNotifyResponse.fail(e.getMessage());
        }
        // System.out.println(xmlResult);


        String orderSn = result.getOutTradeNo();
        String payId = result.getTransactionId();
        // 进行更新支付日志表
        orderPayLogMapper.updatePayIdbyOderSn(orderSn,payId);
        List<ByOrderPayLog> orderPayLogList = orderPayLogMapper.getOrderPayLogByStatusAndOrderSn(orderSn);
        if(orderPayLogList.size() > 0){
            return null;
        }
        orderPayLogList = orderPayLogMapper.getOrderPayLogByOrderSn(orderSn);
        // --------------------------------------进行判断当前是支付订单还是购买优惠券的订单------------------------------------
        ByOrderPayLog orderPayLog = orderPayLogList.get(0);
        orderPayLog.setStatus("1");
        orderPayLog.setUptime(dateUtilSqlMapper.getNowDateTime());
        orderPayLog.setPayId(payId);
        orderPayLogMapper.updateByOrderPayLog(orderPayLog);

        // 分转化成元  YSXM
//        String totalFee = BaseWxPayResult.fenToYuan(result.getTotalFee());
        System.out.println(orderPayLog.getOrderId());
        System.out.println(orderPayLog.getOrderId().contains("yhq"));
        if(orderPayLog.getOrderId().contains("yhq")){
            ByJzYhq yhqEntity = byJzYhqMapper.getJzYhqByPayId(orderSn);
            yhqEntity.setStatus("1");
            yhqEntity.setUptime(dateUtilSqlMapper.getNowDateTime());
            yhqEntity.setStartdate(dateUtilSqlMapper.getNowDate());
            yhqEntity.setEndtime(dateUtilSqlMapper.getDateAddDay(Integer.parseInt(yhqEntity.getDays())));
            byJzYhqMapper.updateByJzYhq(yhqEntity);// 进行更新优惠券的信息
            ByJz jzEntity = jzMapper.getJzEntityByWxId(yhqEntity.getWxid());
            jzEntity.setQid(yhqEntity.getQid());
            jzEntity.setYhqid(yhqEntity.getId()+"");
            jzEntity.setZk(yhqEntity.getZkl());
            jzEntity.setQstatus("1");
            jzMapper.updateByJz(jzEntity);// 进行更新家长的折扣率的问题

            return null;
        }


        // 进行处理支付任务 通过oderSn进行判断当前支付订单是预付，还是支付订单剩余金额
        List<ByOrder> djList = byOrderMapper.getOrderByYfOrderSn(orderSn);
        ByOrder order = null;
        if(djList.size() > 0){
            order = djList.get(0);
            order.setStatus("3");
            order.setUptime(dateUtilSqlMapper.getNowDateTime());
            // 进行锁定当前帮手的时间
            closeBsTime(order);
            // 支付完成，生成扫描的小程序的码
            wxQrcodeService.createQrCode(order.getId()+"");
        }
        List<ByOrder> payList = byOrderMapper.getOrderPayByOrderSn(orderSn);
        if(payList.size() > 0){
            order = payList.get(0);
            order.setStatus("6");
            order.setUptime(dateUtilSqlMapper.getNowDateTime());

            // 完成一个订单，进行订单的增加
            ByBs bsEntity = bsMapper.selectByBsById(Long.parseLong(order.getBsId()));
            int orderCount = Integer.parseInt(bsEntity.getOrdercount())+1;
            bsEntity.setOrdercount(orderCount+"");

            bsMapper.updateByBs(bsEntity);
        }
        byOrderMapper.updateByOrder(order);
        return null;
    }

    // 进行处理帮手的预约时间，不能被其他人进行抢占了
    public void closeBsTime(ByOrder order){
        String time = order.getTime();
        // 获取订单的帮手 设置的日期数据
        String bsid = order.getBsId();
        String date = order.getDate();
        List<ByBsTime> bsTimeList = bsTimeMapper.getBsTimeForByIdAndDate(bsid, date);
        if(bsTimeList.size() > 0){
            ByBsTime bsTime = bsTimeList.get(0);
            if(time.contains("08:00")){
                bsTime.setEleven("3");
            }
            if(time.contains("09:00")){
                bsTime.setNine("3");
            }
            if(time.contains("10:00")){
                bsTime.setTen("3");
            }
            if(time.contains("11:00")){
                bsTime.setEleven("3");
            }
            if(time.contains("12:00")){
                bsTime.setTwelve("3");
            }
            if(time.contains("13:00")){
                bsTime.setThirteen("3");
            }
            if(time.contains("14:00")){
                bsTime.setFourteen("3");
            }
            if(time.contains("15:00")){
                bsTime.setFifteen("3");
            }
            if(time.contains("16:00")){
                bsTime.setSixteen("3");
            }
            if(time.contains("17:00")){
                bsTime.setSeventeen("3");
            }
            if(time.contains("18:00")){
                bsTime.setEighteen("3");
            }
            bsTimeMapper.updateByBsTime(bsTime);
        }
    }



    @Override
    public ByOrder getOrderByWxId(String wxid) {
        return byOrderMapper.getOrderByWxIdOne(wxid);
    }

    // 进行处理帮手的预约时间，不能被其他人进行抢占了
    public boolean getBsTimeFlag(ByOrder order) {
        String time = order.getTime();
        // 获取订单的帮手 设置的日期数据
        String bsid = order.getBsId();
        String date = order.getDate();
        List<ByBsTime> bsTimeList = bsTimeMapper.getBsTimeForByIdAndDate(bsid, date);
        if(bsTimeList.size() > 0){
            ByBsTime bsTime = bsTimeList.get(0);
            if(time.contains("08:00")){
                String timeHm = bsTime.getEight();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("09:00")){
                String timeHm = bsTime.getNine();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("10:00")){
                String timeHm = bsTime.getTen();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("11:00")){
                String timeHm = bsTime.getEleven();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("12:00")){
                String timeHm = bsTime.getTwelve();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("13:00")){
                String timeHm = bsTime.getThirteen();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("14:00")){
                String timeHm = bsTime.getFourteen();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("15:00")){
                String timeHm = bsTime.getFifteen();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("16:00")){
                String timeHm = bsTime.getSixteen();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("17:00")){
                String timeHm = bsTime.getSeventeen();
                if(timeHm.trim().equals("3")){return true;}
            }
            if(time.contains("18:00")){
                String timeHm = bsTime.getEighteen();
                if(timeHm.trim().equals("3")){return true;}
            }
        }

        return false;
    }
    /**
     * 进行拉起微信支付
     * @param body
     * @param request
     * @return
     */
    @Override
    public Object prepay(JSONObject body, HttpServletRequest request) {
        String wxid = body.getString("wxid"); // 获取微信id
        String id = body.getString("id");  // 获取订单id
        ByWxUser userEntity = wxUserMapper.selectByWxUserById(wxid);
        String orderSn = IdUtils.simpleUUID(); // 进行生成订单编号
        // 进行更新订单信息
        ByParam dj = paramMapper.selectByParamById(Long.parseLong("1"));
        ByParam sxf = paramMapper.selectByParamById(Long.parseLong("2"));
        ByOrder order = byOrderMapper.selectByOrderById(Long.parseLong(id));
        // 进行判断当前帮手的时间是否被占用，如果被占用，就不能拉起微信支付，进行付款了
        boolean flag = getBsTimeFlag(order);
        if(flag){
            JSONObject json = new JSONObject();
            json.put("error","400");
            json.put("msg","当前帮手档期已被预约，请更换帮手时间！");
            return json;
        }
        order.setDjPayId(orderSn);
        order.setDprice(BigDecimal.valueOf(Double.parseDouble(dj.getVal())));
        order.setOrderprice(BigDecimal.valueOf(Double.parseDouble(sxf.getVal())));
        byOrderMapper.updateByOrder(order);

        // 进行生成支付日志_____进行保存
        ByOrderPayLog orderPayLog = new ByOrderPayLog();
        orderPayLog.setOrderSn(orderSn);
        orderPayLog.setPrice((Double.parseDouble(dj.getVal())+Double.parseDouble(sxf.getVal()))+"");
        orderPayLog.setAddtime(dateUtilSqlMapper.getNowDateTime());
        orderPayLog.setOrderId(id);
        orderPayLog.setWxId(wxid);
        orderPayLogMapper.insertByOrderPayLog(orderPayLog);


        WxPayMpOrderResult result = null;
        try {
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setOutTradeNo(orderSn);
            orderRequest.setOpenid(userEntity.getWeixinOpenid());
            orderRequest.setBody("订单：" + orderSn);
            // 元转成分
            int fee = 0;
            double djprice = Double.parseDouble(dj.getVal())+Double.parseDouble(sxf.getVal());
            BigDecimal actualPrice = BigDecimal.valueOf(djprice); //order.getActualPrice();
            fee = actualPrice.multiply(new BigDecimal(100)).intValue();
            orderRequest.setTotalFee(fee);
            orderRequest.setSpbillCreateIp(IpUtils.getIpAddr(request));
            result = wxPayService.createOrder(orderRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void stopOrder(JSONObject json) {
        String id = json.getString("id");
        String wxid = json.getString("wxid");
        // *****************************进行判断当前用户是否有停止打学时的权限*************************************
        List<JSONObject> list = byOrderMapper.getOderByBsIdWxId(id, wxid);
        if(list.size() == 0){
            System.out.println("当前用户没有结束订单的权限！");
            return;
        }
        byOrderMapper.stopOrder(id);// 进行更新停止打学时的时间

        ByOrder entity = byOrderMapper.selectByOrderById(Long.parseLong(id));
        String mtime = byOrderMapper.orderMINUTE(id);// 获取帮手上课的时间
        // **************************获取帮手的每小时和每分钟的金额**********************************
        JSONObject bsJson = bsMapper.getBsPrice(entity.getBsId());
        String hprice = bsJson.getString("hprice");
        String mprice = bsJson.getString("mprice");
        // *************************不足一小时的按照一小时计算*********************************************
        int hour = 1;//Integer.parseInt(mtime)/60;
        int min = 0;//Integer.parseInt(mtime)%60;
        if(Integer.parseInt(mtime) > 60){
            hour = Integer.parseInt(mtime)/60;
            min = Integer.parseInt(mtime)%60;
        }
        // 进行计算总价
//        double totalPrice = 0;
        double totalPrice = Double.parseDouble(hprice)*hour+min*Double.parseDouble(mprice); // 获取订单的总金额
        entity.setAllprice(BigDecimal.valueOf(totalPrice));

        // 获取家长的折扣  这里应该获取家长的微信id
        ByJz jz = jzMapper.getJzEntityByWxId(entity.getWxId());
        entity.setZk(jz.getZk());// 折扣
        // 进行计算折扣金额  进行保留小数点后2位
        double zkje = totalPrice*(100-Integer.parseInt(jz.getZk()))/100;
        BigDecimal twoDob = new BigDecimal(zkje);
        zkje = twoDob.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
        entity.setYhje(zkje+"");

        double dprice = Double.parseDouble(entity.getDprice() + "");
        // 付款金额 = 总金额 - 定金  - 折扣金额
        double payPrice = totalPrice - dprice - zkje;
        entity.setPayprice(BigDecimal.valueOf(payPrice));
        entity.setStatus("5");

        entity.setUptime(dateUtilSqlMapper.getNowDateTime());
        //进行生成支付小程序码
        wxQrcodeService.createPayQrCode(id);

        byOrderMapper.updateByOrder(entity);
    }


    public static void main(String[] args) {
        System.out.println(110/60);
    }

    @Override
    public void startOrder(JSONObject json) {
        String id = json.getString("id");
        String wxid = json.getString("wxid");

        byOrderMapper.startOrder(id,wxid);
    }

    @Override
    public void quitOrder(JSONObject json) {
        String id = json.getString("id");
        byOrderMapper.quitOrder(id);
    }

    @Override
    public List<JSONObject> getOrderByWxid(JSONObject json) {
        String wxid = json.getString("wxid");
        String status = json.getString("status");
        String code = json.getString("code");
        if(code.trim().equals("1")){ // 家长端的订单获取
            if(status.equals("1")){//获取全部
                return byOrderMapper.getOrderByWxId(wxid);
            }else{// 根据状态进行加载数据
                if(status.equals("2")){
                    status = "1";
                }
                return byOrderMapper.getOrderByWxIdAndStatus(wxid,status);
            }
        }

        // 帮手端的订单数据获取
        if(code.trim().equals("0")){
            if(status.equals("1")){//获取全部
                return byOrderMapper.getOderByBsWxId(wxid);
            }else{// 根据状态进行加载数据
                if(status.equals("2")){
                    status = "1";
                }
                return byOrderMapper.getOrderByBsWxIdAndStatus(wxid,status);
            }
        }
        return null;
    }

    @Override
    public void savaJzWxOrder(JSONObject json) {
        ByOrder order = new ByOrder();
        // -------------------进行Wx订单记录-------------------------
        String wxid = json.getString("wxid");
        order.setWxId(wxid);
        // ------------------时间跟踪----------------------------------
        order.setAddtime(dateUtilSqlMapper.getNowDateTime());
        order.setUptime(dateUtilSqlMapper.getNowDateTime());
        // ----------------------跟进微信的id获取家长的信息---------设置家长的订单信息---------------------------
        ByJz jzEntity = jzMapper.getJzEntityByWxId(wxid);
        order.setJzId(jzEntity.getId()+"");
        order.setLxr(jzEntity.getName());
        order.setPhone(jzEntity.getPhone());
        order.setAddress(jzEntity.getAddr()+jzEntity.getAddrDetail());
        // --------------------------绑定帮手ID----------------------------
        String bsid = json.getString("bsid");
        order.setBsId(bsid);
        // -----------------------设置要上的科目-------------------------
        String subjectResult = json.getString("subjectResult");
        order.setKm(subjectResult);
        // -----------------------设置要上课的时间-------------------------------
        String timeResult = json.getString("timeResult");
        order.setTime(timeResult);
        // ---------------------------设置日期---------------------------------------
        String date = json.getString("date");
        order.setDate(date);
        // -------------------------------设置备注-----------------------------
        String remark = json.getString("remark");
        order.setRemark(remark);


        byOrderMapper.insertByOrder(order);
    }

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public ByOrder selectByOrderById(Long id)
    {
        return byOrderMapper.selectByOrderById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param byOrder 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<ByOrder> selectByOrderList(ByOrder byOrder)
    {
        return byOrderMapper.selectByOrderList(byOrder);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param byOrder 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertByOrder(ByOrder byOrder)
    {
        return byOrderMapper.insertByOrder(byOrder);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param byOrder 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateByOrder(ByOrder byOrder)
    {
        return byOrderMapper.updateByOrder(byOrder);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteByOrderByIds(Long[] ids)
    {
        return byOrderMapper.deleteByOrderByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteByOrderById(Long id)
    {
        return byOrderMapper.deleteByOrderById(id);
    }

    @Override
    public String isStartOrEnd(String orderid) {
        return byOrderMapper.isStartOrEnd(orderid);
    }

    /**
     * 选中优惠券
     * @param wxid
     * @param yhqId
     * @param orderId
     * @return
     */
    @Override
    public int updateMoney(String wxid, String yhqId, String orderId) {
        //先获取优惠券代表的金额
        BigDecimal yhMoney = byCouponUserMapper.getYhqById(yhqId);
        //将优惠券的选中状态改为1
        byCouponUserMapper.updateStatus(yhqId);
        // 去更新订单表的尾款金额
        return  byOrderMapper.updateMoney(orderId, yhMoney,wxid);
    }


    /**
     * 取消选择优惠券
     * @param yhqId
     * @return
     */
    @Override
    public int updateYhqStatus(String yhqId,String orderId) {
        // 将优惠券选中状态改为1
        byCouponUserMapper.updateYhqStatus(yhqId);
        // 得到优惠券金额
        BigDecimal yhMoney = byCouponUserMapper.getYhqById(yhqId);
        // 根据订单号将尾款还原
        return byOrderMapper.resetMoney(orderId, yhMoney);
    }

    @Override
    public int successPay(String yhqId, String orderId, String userid) {
        if (StringUtils.isNotEmpty(yhqId)){
            // 正常状态下直接根据yhqid删除
            byCouponUserMapper.applyById(yhqId);
        }else {
            // 用户返回在支付时出现异常找不到yhqid，所以用userid删除选中的优惠券
            byCouponUserMapper.applyByUserId(userid);
        }
        return byOrderMapper.updateStatusById(orderId);
    }
}
